package com.example.jbmsuppliers.sinopec.doorjurisd;

import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;

import com.example.jbmsuppliers.sinopec.utlis.SaveOpenKeyManage;
import com.example.jbmsuppliers.sinopec.view.MyLog;
import com.jbm.jbmsupplier.util.IEGuardKey;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;




public class SensorService extends Service {
    private SensorManager sensorManager;
    private Vibrator vibrator;
    private float lastY = 0;
    private float lastZ = 0;
    private long lastUpdateTime = 0;
    private float lastX = 0;
    private int con = -5;
    private Timer timer;
    private SharedPreferences sharedPreferenceserson;
    private int intfz;
    public static final int SERSONWINSOW = 0001;
    private DoorOpenBlue doorOpenBlue;
    private ArrayList<IEGuardKey> arr;

    @Override
    public void onCreate() {
        //重力感应传感器初始化
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
         doorOpenBlue=new DoorOpenBlue(SensorService.this,handler);
        arr = new SaveOpenKeyManage(SensorService.this).setgainOpenKey();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (sensorManager != null) {// 注册监听器
            Sensor sensor = sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
            sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_UI);
            // 第一个参数是Listener，第二个参数是所得传感器类型，第三个参数值获取传感器信息的频率
            timer = new Timer();
            timer.schedule(new Timertask(), 0, 5000);
        }
        return START_STICKY;
    }


    class Timertask extends TimerTask {

        @Override
        public void run() {
            sharedPreferenceserson = getSharedPreferences("sersonzhi", Activity.MODE_PRIVATE);//来保存开关状态
            intfz = sharedPreferenceserson.getInt("serxon", 1000);
            MyLog.e(intfz+"");
        }
    }

    private SharedPreferences sharedPreferences;
    private SensorEventListener sensorEventListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            if (SensorManager.SENSOR_ACCELEROMETER == event.sensor.getType()) {
                long currentUpdateTime = System.currentTimeMillis(); //现在检测时间
                // 两次检测时间的间隔
                long timeInterval = currentUpdateTime - lastUpdateTime;
                // 判断是否达到了检测时间间隔
                if (timeInterval < 100) {
                    return;
                }
                //现在的时间变成last时间
                lastUpdateTime = currentUpdateTime;
                // 获得x,y,z坐标
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
                // 获得x,y,z的变化值
                float deltaX = x - lastX;
                float deltaY = y - lastY;
                float deltaZ = z - lastZ;
                // 将现在的坐标变成last坐标
                lastX = x;
                lastY = y;
                lastZ = z;
                //计算速度阀值
                double s = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / timeInterval * 10000;
                //达到速度阀值，执行振动
                if (s >= intfz/*&&vibrator.hasVibrator()*/) { //执行震动功能
                    con += 1;
                    if (con < 0) {
                        new Timer().schedule(new TimerTask() {
                            @Override
                            public void run() {
                                con = -5;
                            }
                        }, 5000);
                        return;
                    } else if (con > 0) {
                        sharedPreferences=getSharedPreferences("open_key_judge", Activity.MODE_PRIVATE);
                        int open = sharedPreferences.getInt("intopen", 0);
                        if (open!=1){

                            if (arr==null){
                                return;}
                            if (arr.size()>0)
                            doorOpenBlue.OpenDoorGather("SerSon",null,SensorService.this,null,null);
                        }
                        con = -5;
                        return;
                    }
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        sensorManager.unregisterListener(sensorEventListener);
    }

    Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what){
            case SERSONWINSOW:{
                MyLog.e("清空摇一摇");
                getSharedPreferences("open_key_judge", Activity.MODE_PRIVATE).edit().clear().commit();
            }

        }


    }
};
}
